<template>
  <div >
    <van-nav-bar
      title="添加版本"
    />
    <div class="container">
      <van-uploader accept="application/vnd.android.package-archive" class="mtop10" :after-read="onFileSeleted">
        <van-card
          title="安装包"
          :desc="originFile?originFile.file.name:'选择文件'"
          :price="originFile?getFilesize(originFile.file.size):''"
          :thumb="icon"
          currency=""
        />
      </van-uploader>
      <van-cell-group v-if="originFile">
        <van-cell required title="AppType" :value="appType" @click="show=true" />
        <van-cell required title="buildType" :value="buildType" @click="show1=true" />
        <van-field
          v-model="versionName"
          required
          readonly
          clearable
          input-align="right"
          label="versionName"
        />
        <van-field
          v-model="versionCode"
          required
          readonly
          clearable
          input-align="right"
          label="versionCode"
        />
      </van-cell-group>
      <van-actionsheet v-model="show" :actions="actions" />
      <van-actionsheet v-model="show1" :actions="buildTypes" />
      <van-button  :disabled="!submitEnable" class="mtop10" size="large" type="primary" :loading="loading" @click="save">保存</van-button>
    </div>
  </div>
</template>
<script>
const iconUrl = require('../assets/icon_apk.png')
import { Toast } from 'vant'
export default {
  name: 'upload',
  data() {
    return {
      show: false,
      show1: false,
      icon: iconUrl,
      originFile: null,
      loading: false,
      actions: [],
      buildTypes: [],
      versionName: '',
      versionCode: '',
      appType: '',
      buildType: ''
    }
  },
  mounted() {
    this.getAppTypes()
    this.getBuildTypes()
  },
  computed: {
    submitEnable() {
      return this.originFile != null
    }
  },
  methods: {
    getBuildTypes() {
      this.buildTypes = ['develop', 'product'].map(d => {
        return {
          name: d,
          callback: () => {
            this.show1 = false
            this.buildType = d
          }
        }
      })
      if (this.buildTypes.length > 0) {
        this.buildType = this.buildTypes[0].name
      }
    },
    getAppTypes() {
      this.$axios.get('/api/appTypes').then(res => {
        if (res.data.result == 'success') {
          this.actions = res.data.data.map(d => {
            return {
              name: d,
              callback: () => {
                this.show = false
                this.appType = d
              }
            }
          })
          if (this.actions.length > 0) {
            this.appType = this.actions[0].name
          }
        } else {
          console.log(res.data.msg)
        }
      })
    },
    getBlob(buffer, format) {
      try {
        return new window.Blob(buffer, { type: format })
      } catch (e) {
        const bb = new (window.BlobBuilder ||
          window.WebKitBlobBuilder ||
          window.MSBlobBuilder)()
        buffer.forEach(buf => {
          bb.append(buf)
        })
        return bb.getBlob(format)
      }
    },
    getFilesize(size) {
      return Math.floor(size / 1024) + 'K'
    },
    onFileSeleted(file) {
      this.originFile = file
      console.log(file)
      if (this.originFile) {
        this.versionName = file.file.name.substring(
          file.file.name.indexOf('V') + 1,
          file.file.name.indexOf('_', file.file.name.indexOf('V') + 1)
        )
        this.versionCode = file.file.name.substring(
          file.file.name.indexOf('00_') + 3,
          file.file.name.indexOf('.apk')
        )
      }
    },
    save() {
      this.loading = true
      const file = this.originFile
      const { type } = file.file
      const text = window.atob(file.content.split(',')[1])
      const buffer = new Uint8Array(text.length)
      for (let i = 0; i < text.length; i++) {
        buffer[i] = text.charCodeAt(i)
      }
      const blob = this.getBlob([buffer], type)
      const param = new window.FormData()
      param.append('file', blob, file.file.name)
      const config = {
        headers: { 'Content-Type': 'multipart/form-data' }
      }
      const data = {
        versionCode: this.versionCode,
        versionName: this.versionName,
        appType: this.appType,
        buildType: this.buildType
      }
      for (var key in data) {
        param.append(key, data[key])
      }
      this.$axios.post('/api/addVersion', param, config).then(res => {
        this.loading = false
        if (res.data.result == 'success') {
          this.$dialog.confirm({
            message: '保存成功，是否立即发布？'
          })
            .then(() => {
              const data = {
                versionCode: res.data.data.VersionCode,
                versionName: res.data.data.VersionName,
                appType: res.data.data.AppType,
                buildType: res.data.data.BuildType,
                downloadUrl: res.data.data.DownloadUrl,
                objectId: res.data.data.objectId
              }
              this.$axios.post('/api/publishVersion', data).then(res => {
                if (res.data.result == 'success') {
                  Toast('发布成功')
                } else {
                  Toast(res.data.msg || '发布成功')
                }
              })
            })
            .catch(() => {
              // on cancel
            })
        } else {
          Toast(res.data.msg || '上传失败')
        }
      })
    }
  }
}
</script>

<style scoped>
.page {
}
.container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  padding-left: 12px;
  padding-right: 12px;
}
.mtop10 {
  margin-top: 10px;
}
.row {
  flex-direction: row;
}
</style>
